<?php

namespace App\Http\Controllers\Api\v3;

use App\Http\Controllers\Controller;
use App\Models\Api\ZodiacSign;
use App\Models\Api\WeeklyHoroscope;
use Illuminate\Http\Request;

class StarAstroController extends Controller
{
    /**
     * 获取星座信息
     *
     * @param Request $request 请求对象
     * @return mixed 返回响应数据
     */
    public function index(Request $request)
    {
        $inSign = $request->input('in_sign');
        if(empty($inSign)) {
            return show(config('code.error'), '请输入星座ID', []);
        }
        //查询总体分析
        $overall = ZodiacSign::where('type', 'overall')
            ->where('in_sign', $inSign)
            ->with(['weeklyHoroscopes' => function ($query) {
                $query->latest()->get();
            }])
            ->get();

        //查询关系分析数据
        $relation = ZodiacSign::where('type', 'relation')
            ->where('in_sign', $inSign)
            ->with(['weeklyHoroscopes' => function ($query) {
                $query->latest()->get();
            }])
            ->get();

        if ($overall->isEmpty() || $relation->isEmpty()) {
            return show(config('code.error'), '星座数据未找到', []);
        }

        // 输出结果
        $data = [
            'in_sign' => $inSign,
            'overall' => $this->formatZodiacSign($overall, 'overall'),
            'relation' => $this->formatZodiacSign($relation, 'relation'),
            'week' => $this->getWeeklyHoroscope($inSign),
        ];

       return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 使用map方法遍历$signs集合，并对每个$sign对象进行格式化处理。
     * 返回一个新的集合，其中包含了格式化后的数组。
     *
     * @param  array $signs 星座信息集合或数组
     * @param string $type 格式化类型（在此函数内部并未使用）
     * @return // 格式化后的星座信息集合
     */
    private function formatZodiacSign($signs, $type)
    {
        return $signs->map(function ($sign) use ($type) {
            return [
                'id' => $sign->id,
                'title' => $sign->title,
                'avatar' => $sign->avatar,
                'tags' => $sign->tags,
                'content' => $sign->content,
                'in_sign' => $sign->in_sign,
                'relation_id' => $sign->relation_id,
                'tip' => $sign->tip,
                'tags_color' => $sign->tags_color,
                'tags_bg_color' => $sign->tags_bg_color,
            ];
        });
    }


    /**
     * 获取指定星座的本周运势
     *
     * @param int $inSign 星座ID
     *
     * @return array 包含运势标题、简介和内容的数组
     */
    private function getWeeklyHoroscope($inSign)
    {
        $horoscope = WeeklyHoroscope::latest()->where('zodiac_sign_id', $inSign)->first();

        return [
            'title' => $horoscope->title,
            'introduction' => $horoscope->introduction,
            'content' => $horoscope->content,
        ];
    }
}
